<template>
    <!-- 主搜索和操作按钮区域 -->
    <form class="form">
        <!-- 网络搜索弹出框 -->
        <a-popover class="a-popover" title="搜索网络结果" placement="bottomLeft" trigger="click">
            <template #content>
                <!-- 搜索结果列表 -->
                <a-list style="white-space: nowrap" item-layout="horizontal" :data-source="list">
                    <template #renderItem="{ item }">
                        <a-list-item style="padding-left: 12px; cursor: pointer;" @click="webSearch">
                            <a-list-item-meta :description="item.description">
                                <template #title>
                                    <span>{{ item.title }}</span>
                                </template>
                                <template #avatar>
                                    <a-avatar shape="square" :src="item.avatar" />
                                </template>
                            </a-list-item-meta>
                        </a-list-item>
                    </template>
                </a-list>
            </template>

            <!-- 搜索输入框 -->
            <div class="group">
                <svg class="icon" aria-hidden="true" viewBox="0 0 24 24">
                    <g>
                        <path
                            d="M21.53 20.47l-3.66-3.66C19.195 15.24 20 13.214 20 11c0-4.97-4.03-9-9-9s-9 4.03-9 9 4.03 9 9 9c2.215 0 4.24-.804 5.808-2.13l3.66 3.66c.147.146.34.22.53.22s.385-.073.53-.22c.295-.293.295-.767.002-1.06zM3.5 11c0-4.135 3.365-7.5 7.5-7.5s7.5 3.365 7.5 7.5-3.365 7.5-7.5 7.5-7.5-3.365-7.5-7.5z">
                        </path>
                    </g>
                </svg>
                <input placeholder="搜索" v-model="keyword" class="input">
            </div>
        </a-popover>&nbsp;&nbsp;

        <!-- 添加/群聊操作弹出框 -->
        <a-popover class="a-popover" placement="bottom" trigger="hover">
            <template #content>
                <ul>
                    <li>
                        <a-button type="text" @click="visibleInitiate = true">
                            <template #icon>
                                <CommentOutlined />
                            </template>
                            发起群聊
                        </a-button>
                    </li>
                    <li>
                        <a-button type="text" @click="visibleAdd = true">
                            <template #icon>
                                <UserAddOutlined />
                            </template>
                            添加朋友
                        </a-button>
                    </li>
                </ul>
            </template>
            <div class="add">
                <a-button class="add">+</a-button>
            </div>
        </a-popover>

        <!-- 添加朋友模态框 -->
        <a-modal v-model:open="visibleAdd" width="400px" :footer="null" title="添加朋友" keyboard>
            <a-input-search style="border-bottom: 1px solid #e0e0e0" :bordered="false" placeholder="搜索好友账号（用户名）"
                v-model:value="username">
                <template #prefix>
                    <SearchOutlined />
                </template>
                <template #enterButton>
                    <a-button @click="searchUser">
                        <SendOutlined />
                    </a-button>
                </template>
            </a-input-search>

            <!-- 搜索到的用户信息卡片 -->
            <a-card style="margin-top: 15px">
                <a-list item-layout="horizontal" :data-source="userInfo">
                    <template #renderItem="{ item }">
                        <a-list-item>
                            <a-list-item-meta :description="'创建时间：' + item.create_at.slice(0, 10)">
                                <template #title>
                                    <span>{{ item.username }} - ({{ item.nickname }})</span>
                                </template>
                                <template #avatar>
                                    <a-avatar :src="baseURL + item.avatar" />
                                </template>
                            </a-list-item-meta>
                        </a-list-item>
                        <a-list-item class="add-friend">
                            <button type="button" class="button" @click="friendshipAdd(item.id)">
                                <span class="button__text">添加朋友</span>
                                <span class="button__icon"><svg xmlns="http://www.w3.org/2000/svg" width="24"
                                        viewBox="0 0 24 24" stroke-width="2" stroke-linejoin="round"
                                        stroke-linecap="round" stroke="currentColor" height="24" fill="none"
                                        class="svg">
                                        <line y2="19" y1="5" x2="12" x1="12"></line>
                                        <line y2="12" y1="12" x2="19" x1="5"></line>
                                    </svg></span>
                            </button>
                        </a-list-item>
                    </template>
                </a-list>
            </a-card>
        </a-modal>

        <!-- 发起群聊模态框 -->
        <a-modal v-model:open="visibleInitiate" width="650px" title="发起群聊" @ok="initiateGroupChat" okText="完成"
            cancelText="取消" :closable="false" :keyboard="true" :destroyOnClose="true">
            <a-input :bordered="false" placeholder="输入昵称：搜索好友" v-model:value="nickname">
                <template #prefix>
                    <SearchOutlined />
                </template>
            </a-input>

            <!-- 群聊选择界面 -->
            <div class="card-content">
                <div class="left-card">
                    <details open>
                        <summary style="font-size: 14px">联系人 <span class="total">{{ friendList.length }}</span></summary>
                        <a-list item-layout="horizontal" :data-source="friendList" :split="false">
                            <template #renderItem="{ item }">
                                <a-list-item @click="toggleUserSelection(item.other_user_id)"
                                    style="cursor: pointer; display: flex; align-items: center;">
                                    <!-- 复选框 -->
                                    <a-checkbox style="position: relative; left: -10px;"
                                    :checked="selectedUserTids.includes(item.other_user_id)" />
                                    <!-- 用户信息 -->
                                    <a-list-item-meta>
                                        <template #title>
                                            <span style="position: relative; top: 6px; font-size: 14px;">
                                                {{ item.other_user_nickname }}
                                            </span>
                                        </template>
                                        <template #avatar>
                                            <a-avatar shape="square" :src="baseURL + item.other_user_avatar" />
                                        </template>
                                    </a-list-item-meta>
                                </a-list-item>
                            </template>
                        </a-list>
                    </details>
                </div>
                <div class="divider"></div>
                <div class="right-card">
                    <div class="selected-total" v-show="selectedUsersInfo.length > 0">
                        已选择 {{ selectedUsersInfo.length }} 个联系人
                    </div>
                    <a-list item-layout="horizontal" :data-source="selectedUsersInfo" :split="false">
                        <template #renderItem="{ item }">
                            <a-list-item>
                                <template #actions>
                                    <CloseCircleFilled @click="removeUser(item.other_user_id)" />
                                </template>
                                <a-list-item-meta>
                                    <template #title>
                                        <span style="position: relative; top: 6px; font-size: 14px;">{{
                                            item.other_user_nickname }}</span>
                                    </template>
                                    <template #avatar>
                                        <a-avatar shape="square" :src="baseURL + item.other_user_avatar" />
                                    </template>
                                </a-list-item-meta>
                            </a-list-item>
                        </template>
                    </a-list>
                </div>
            </div>
        </a-modal>
    </form>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, inject, watchEffect } from 'vue'
import { CommentOutlined, UserAddOutlined, SearchOutlined, SendOutlined, CloseCircleFilled } from '@ant-design/icons-vue'
import { GetUserSearch_API } from '@/api/user.js'
import { FriendShipList_API, FriendShipAdd_API } from '@/api/friendship.js'
import { GroupChatCreate_API } from '@/api/groupchat.js'
import { message, notification } from 'ant-design-vue'

// 全局配置和注入
const baseURL = import.meta.env.VITE_API_BASE_URL // API基础URL
const socket = inject('socket') // 注入Socket.io实例

// 响应式数据定义
const keyword = ref('') // 搜索关键词
const username = ref('') // 用户名搜索
const nickname = ref('') // 昵称搜索
const visibleAdd = ref(false) // 添加朋友模态框显示状态
const visibleInitiate = ref(false) // 发起群聊模态框显示状态
const userInfo = ref([]) // 用户信息列表
const friendList = ref([]) // 好友列表
const selectedUserTids = ref([]) // 当前被选中的用户 tid 列表

// 网络搜索结果列表
const list = reactive([
    {
        title: '搜索网络结果',
        description: '必应搜索',
        avatar: 'https://img0.baidu.com/it/u=3592826660,233192995&fm=253&fmt=auto&app=138&f=PNG?w=500&h=500'
    }
])

// 搜索用户： 添加朋友
const searchUser = async () => {
    const { data: res } = await GetUserSearch_API(username.value)
    userInfo.value = res.data
}

// 计算属性：已选用户信息
const selectedUsersInfo = computed(() => {
    return friendList.value.filter(item => selectedUserTids.value.includes(item.other_user_id));
});

// 切换用户选中状态
const toggleUserSelection = (uid) => {
  const index = selectedUserTids.value.indexOf(uid);
  if (index === -1) {
    selectedUserTids.value.push(uid); // 未选中则选中
  } else {
    selectedUserTids.value.splice(index, 1); // 已选中则取消
  }
};

/**
 * 执行网络搜索
 */
const webSearch = () => {
    window.electron.webSearchInvoke(keyword.value)
    keyword.value = ''
}

/**
 * 获取好友列表
 */
const friendshipList = async () => {
    const { data: res } = await FriendShipList_API(1, nickname.value)
    friendList.value = res.data
}

/**
 * 添加好友
 * @param {number} tid - 目标用户ID
 */
const friendshipAdd = async (tid) => {
    const { data: res } = await FriendShipAdd_API(tid)
    if (res.code === 200) {
        message.success(res.message)
        socket.emit('friendship update notification', 0, tid)
    } else {
        message.error(res.message)
    }
}

/**
 * 选择用户（用于创建群聊）
 * @param {Object} item - 用户项
 */
const selectUser = (item) => {
    const index = selectedUserTids.value.indexOf(item.other_user_id);
    if (index === -1) {
        selectedUserTids.value.push(item.other_user_id);
    } else {
        selectedUserTids.value.splice(index, 1);
    }
};

/**
 * 删除用户
 * @param {number} tid - 用户ID
 */
const removeUser = (tid) => {
    const index = selectedUserTids.value.indexOf(tid);
    if (index !== -1) {
        selectedUserTids.value.splice(index, 1);
    }
};

/**
 * 发起群聊
 */
const initiateGroupChat = async () => {
    if (selectedUserTids.value.length < 2) {
        message.warning('请选择至少两名或以上的用户，才能发起群聊')
        return
    }
    const nameList = selectedUsersInfo.value.map(item => item.other_user_nickname)
    const name = nameList.join('、')
    const members = selectedUsersInfo.value.map(item => ({
        uid: item.other_user_id,
        role: 'member',
        join_at: new Date().getTime(),
        left_at: null,
        is_muted: false,
        muted_until: null,
        status: 1
    }))
    
    const { data: res } = await GroupChatCreate_API(name, members)
    if (res.code === 200) {
        message.success(res.message)
        visibleInitiate.value = false
        selectedUserTids.value = []
        socket.emit('group-notification', members)
    } else {
        message.error(res.message)
    }
}

// 监听昵称变化，实现搜索防抖
let timer = null
watchEffect(() => {
    if (nickname.value.trim() !== '') {
        timer = setTimeout(() => {
            friendshipList()
        }, 1000)
    } else {
        friendshipList()
    }
})

// 组件挂载时执行
onMounted(() => {
    friendshipList() // 初始化好友列表
    // 监听好友添加通知
    socket.on('friendship add notification', (message) => {
        notification.success({
            key: 'friendship add notification',
            message: '好友提醒',
            description: message
        })
    })
})

// 组件卸载时清理
onUnmounted(() => {
    clearTimeout(timer) // 清理定时器
})
</script>

<style scoped>
/* 主表单样式 */
.form {
    width: 100%;
    height: 100%;
    position: relative;
    background-color: #F7F7F7;
    z-index: 888;
    display: flex;
    justify-content: center;
    align-items: center;
    -webkit-app-region: drag;
}

/* 弹出框样式 */
.a-popover {
    padding: 0;
    margin: 0;
    -webkit-app-region: no-drag;
}

/* 搜索框组样式 */
.group {
    display: flex;
    line-height: 28px;
    align-items: center;
    position: relative;
    max-width: 160px;
}

/* 输入框样式 */
.input {
    height: 28px;
    line-height: 28px;
    padding: 0 1rem;
    width: 100%;
    padding-left: 2.5rem;
    border: 2px solid transparent;
    border-radius: 4px;
    outline: none;
    background-color: #EDEDED;
    color: #0d0c22;
    transition: .3s ease;
    font-size: 12px;
}

.input::placeholder {
    color: #777;
}

/* 搜索图标样式 */
.icon {
    position: absolute;
    left: 1rem;
    fill: #777;
    width: 1rem;
    height: 1rem;
}

/* 添加按钮样式 */
.add {
    width: 28px;
    height: 28px;
    background-color: #EDEDED;
    color: #b7b2b2;
    margin: 0;
    padding: 0;
    border: none;
    border-radius: none;
    outline-color: none;
}

/* 无序列表样式 */
ul {
    list-style: none;
}

ul li {
    padding-bottom: 5px;
}

/* 添加好友按钮样式 */
.add-friend {
    display: flex;
    justify-content: center;
    align-items: center;
    padding-bottom: 0;
}

/* 按钮动画样式 */
.button {
    position: relative;
    width: 150px;
    height: 40px;
    cursor: pointer;
    display: flex;
    align-items: center;
    border: 1px solid #34974d;
    background-color: #3aa856;
}

.button,
.button__icon,
.button__text {
    transition: all 0.3s;
}

.button .button__text {
    transform: translateX(30px);
    color: #fff;
    font-weight: 600;
}

.button .button__icon {
    position: absolute;
    transform: translateX(109px);
    height: 100%;
    width: 39px;
    background-color: #34974d;
    display: flex;
    align-items: center;
    justify-content: center;
}

.button .svg {
    width: 30px;
    stroke: #fff;
}

.button:hover {
    background: #34974d;
}

.button:hover .button__text {
    color: transparent;
}

.button:hover .button__icon {
    width: 148px;
    transform: translateX(0);
}

.button:active .button__icon {
    background-color: #2e8644;
}

.button:active {
    border: 1px solid #2e8644;
}

/* 群聊选择界面样式 */
.card-content {
    height: 400px;
    display: grid;
    grid-template-columns: 1fr 1px 1fr;
    border-top: 1px solid #e0e0e0;
    border-bottom: 1px solid #e0e0e0;
}

.divider {
    border: 1px solid #E0E0E0;
}

.left-card {
    background-color: #F7F7F7;
}

.right-card {
    background-color: #FFFFFF;
}

.selected-total {
    font-size: 12px;
    color: #D5D5D5;
    text-align: right;
}

.left-card,
.right-card {
    overflow-y: scroll;
    padding: 10px;
    position: relative;
}
</style>